//
//  MS_ElectronicStopViewController.m
//  WisdomTheTramAPP
//
//  Created by 王金明 on 16/7/6.
//  Copyright © 2016年 DouJin. All rights reserved.
//

#import "SJZScanCodeController.h"
#import <AVFoundation/AVFoundation.h>
#import "SJZScanView.h"

@interface SJZScanCodeController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>

@property(strong,nonatomic)AVCaptureDevice*device;
@property(nonatomic,strong)AVCaptureDeviceInput*input;
@property(nonatomic,strong)AVCaptureMetadataOutput*output;
@property(nonatomic,strong)AVCaptureSession*session;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer*preview;
@property(nonatomic,strong)UILabel*content;
@property(nonatomic,strong)UIView *scanWindow; //扫描的窗口

@property(nonatomic,strong)UIImageView*animationView;

@property(nonatomic,strong)SJZScanView *bottomView;

@end


//#define ClipRect CGRectMake((_preview.bounds.size.width-240)/2.0, (self.view.bounds.size.height-64-240)/2.0, 240, 240)
#define ClipRect CGRectMake((_preview.bounds.size.width-240)/2.0, 100, 240, 240)

#define top CGRectMake(ClipRect.origin.x, ClipRect.origin.y, ClipRect.size.width, 32)
#define bottom CGRectMake(ClipRect.origin.x, ClipRect.size.height-32+ClipRect.origin.y, ClipRect.size.width, 32)

@implementation SJZScanCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"扫描优惠券";
    AVAuthorizationStatus videoState=   [AVCaptureDevice  authorizationStatusForMediaType:AVMediaTypeVideo];
    if(videoState==AVAuthorizationStatusDenied){
        UIImageView *lockView = [[UIImageView alloc] init];
        lockView.image = [UIImage imageNamed:@"lock"];
        lockView.frame = CGRectMake(0, 64, self.view.frame.size.width, 60);
        lockView.center=CGPointMake(self.view.center.x, self.view.center.y-80);
        lockView.contentMode = UIViewContentModeCenter;
        [self.view addSubview:lockView];
        UILabel *lockLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, lockView.y+lockView.height+20, self.view.frame.size.width - 40,100)];
        lockLbl.text = @"请在iPhone的\"设置-隐私\"选项中允许访问相册和相机";
        lockLbl.textColor=[UIColor blackColor];
        lockLbl.numberOfLines = 0;
        lockLbl.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:lockLbl];
        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请在iPhone的\"设置-隐私\"选项中允许访问相册和相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    
    [self setScan];
    [self setClipRound];
    [self setScanWindow];
    [self setBottomView];
}

- (void)setScanWindow{
    
    self.scanWindow = [[UIView alloc] initWithFrame:CGRectMake(ClipRect.origin.x - 5, ClipRect.origin.y - 5, ClipRect.size.width + 10, ClipRect.size.height + 10)];
    self.scanWindow.clipsToBounds = YES;
    self.scanWindow.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.scanWindow];
    
    CGFloat scanWindowH = self.scanWindow.width;
    CGFloat scanWindowW = self.scanWindow.height;
    CGFloat buttonWH = 18;
    
    UIButton *topLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWH, buttonWH)];
    [topLeft setImage:[UIImage imageNamed:@"scan_1"] forState:UIControlStateNormal];
    [_scanWindow addSubview:topLeft];
    
    UIButton *topRight = [[UIButton alloc] initWithFrame:CGRectMake(scanWindowW - buttonWH, 0, buttonWH, buttonWH)];
    [topRight setImage:[UIImage imageNamed:@"scan_2"] forState:UIControlStateNormal];
    [_scanWindow addSubview:topRight];
    
    UIButton *bottomLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, scanWindowH - buttonWH, buttonWH, buttonWH)];
    [bottomLeft setImage:[UIImage imageNamed:@"scan_3"] forState:UIControlStateNormal];
    [_scanWindow addSubview:bottomLeft];
    
    UIButton *bottomRight = [[UIButton alloc] initWithFrame:CGRectMake(scanWindowW - buttonWH, scanWindowH - buttonWH, buttonWH, buttonWH)];
    [bottomRight setImage:[UIImage imageNamed:@"scan_4"] forState:UIControlStateNormal];
    [_scanWindow addSubview:bottomRight];
    
}

- (void)setBottomView{
    
    self.bottomView = [[SJZScanView alloc] initWithFrame:CGRectMake(0, 370, kScreenWidth, 300)];
    [self.view addSubview:self.bottomView];
    __weak __typeof (self) weakSelf = self;
    self.bottomView.cancleBlock = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    self.bottomView.shoudianBlock = ^(BOOL isSelceted) {
        [weakSelf turnTorchOn:isSelceted];
    };
    
}

#pragma mark-> 开关闪光灯
- (void)turnTorchOn:(BOOL)on
{
    
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            
            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_session startRunning];
    [self resumeAnimation];

}

//===================================

#pragma mark 恢复动画
- (void)resumeAnimation
{
    CAAnimation *anim = [_animationView.layer animationForKey:@"translationAnimation"];
    if(anim){
        // 1. 将动画的时间偏移量作为暂停时的时间点
        CFTimeInterval pauseTime = _animationView.layer.timeOffset;
        // 2. 根据媒体时间计算出准确的启动动画时间，对之前暂停动画的时间进行修正
        CFTimeInterval beginTime = CACurrentMediaTime() - pauseTime;
        
        // 3. 要把偏移时间清零
        [_animationView.layer setTimeOffset:0.0];
        // 4. 设置图层的开始动画时间
        [_animationView.layer setBeginTime:beginTime];
        
        [_animationView.layer setSpeed:1.0];
        
    }else{
        
        CGFloat scanNetImageViewH = ClipRect.size.width;
        CGFloat scanNetImageViewW = ClipRect.size.width;
        
        _animationView.frame = CGRectMake(5, -scanNetImageViewH + 5, scanNetImageViewW, scanNetImageViewH);
        CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
        scanNetAnimation.keyPath = @"transform.translation.y";
        scanNetAnimation.byValue = @(scanNetImageViewH);
        scanNetAnimation.duration = 1.3;
        scanNetAnimation.repeatCount = MAXFLOAT;
        [_animationView.layer addAnimation:scanNetAnimation forKey:@"translationAnimation"];
        [_scanWindow addSubview:_animationView];
    }
    
}


//===================================

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //动画
//    CAKeyframeAnimation*key=[CAKeyframeAnimation animationWithKeyPath:@"position"];
//    key.duration=3;
//    key.values=@[[NSValue valueWithCGPoint:CGPointMake(top.origin.x, top.origin.y+25)],[NSValue valueWithCGPoint:CGPointMake(bottom.origin.x, bottom.origin.y+25)],[NSValue valueWithCGPoint:CGPointMake(top.origin.x, top.origin.y+25)]];
//    key.repeatCount=NSUIntegerMax;
//    [_animationView.layer addAnimation:key forKey:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_session stopRunning];
}

-(void)setScan{
    //硬件设备
    _device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //输入设备，捕获的
    NSError*error=nil;
    _input=[AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];

    //输出，捕获的东西处理
    _output=[[AVCaptureMetadataOutput alloc]init];
    dispatch_queue_t queue=    dispatch_queue_create("barCode.const", DISPATCH_QUEUE_CONCURRENT);
    [ _output setMetadataObjectsDelegate:self queue:queue];
    
    //链接input和output的
    _session=[[AVCaptureSession alloc]init];
    if ([_session canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
        //视频输入每一帧图像质量的大小
        [_session setSessionPreset:AVCaptureSessionPreset1920x1080];
    }
    if ([_session canAddInput:self.input]&&error==nil) {
        [_session addInput:_input];
    }else {
        NSLog(@"输入input不可用");
    }
    if ([_session canAddOutput:_output]) {
        [_session addOutput:_output];
    }
    //output加入到session才可设置,捕获到的数据是二维码／条形码
    _output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Code];
    
    //预览
    _preview=[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.anchorPoint=CGPointZero;
    _preview.videoGravity=AVLayerVideoGravityResizeAspectFill;
    _preview.frame=CGRectMake(0, 0, self.view.bounds.size.width,self.view.bounds.size.height);
    
    [self.view.layer addSublayer:_preview];
}

-(void)setClipRound{
    //取景框
    UIImageView*imageView=[[UIImageView alloc]initWithFrame:self.preview.bounds];
    imageView.image=[self clipImage:ClipRect];
    imageView.userInteractionEnabled=YES;
    
//    UIImageView*animationView=[[UIImageView alloc]initWithFrame:CGRectMake(top.origin.x-top.size.width/2.0, top.origin.y, top.size.width, top.size.height)];
//    animationView.image=[UIImage imageNamed:@"qrcode_scan_light_green"];

    UIImageView*animationView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"scan_net"]];
    self.animationView = animationView;
//    _animationView.layer.anchorPoint=CGPointZero;
//    [_preview addSublayer:animationView.layer];
    [_preview addSublayer:imageView.layer];
    //设置扫描敏感区域
    [self rectOfInterest:ClipRect];
    
}

-(void)rectOfInterest:(CGRect)rect{
    CGSize size = self.view.bounds.size;
    CGRect cropRect = rect;
    CGFloat p1 = size.height/size.width;
    CGFloat p2 = 1920./1080.;  //使用了1080p的图像输出
    if (p1 < p2) {
        CGFloat fixHeight =_preview.bounds.size.width * 1920. / 1080.;
        CGFloat fixPadding = (fixHeight - size.height)/2;
        //设置识别区域
        _output.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight,
                                            cropRect.origin.x/size.width,
                                            cropRect.size.height/fixHeight,
                                            cropRect.size.width/size.width);
    } else {
        CGFloat fixWidth =_preview.bounds.size.height * 1080. / 1920.;
        CGFloat fixPadding = (fixWidth - size.width)/2;
        _output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                            (cropRect.origin.x + fixPadding)/fixWidth,
                                            cropRect.size.height/size.height,
                                            cropRect.size.width/fixWidth);
    }
    //rectOfInterest是基于图像的大小裁剪的。
}

-(UIImage*)clipImage:(CGRect)rect{
    UIGraphicsBeginImageContextWithOptions(self.preview.bounds.size, NO, 1.0);
    CGContextRef ctf=UIGraphicsGetCurrentContext();
    CGContextAddRect(ctf, self.preview.bounds);
    CGContextSetFillColorWithColor(ctf, [[UIColor blackColor] colorWithAlphaComponent:0.5].CGColor);
    CGContextDrawPath(ctf, kCGPathFill);
    CGContextClearRect(ctf, rect);
    CGContextAddRect(ctf, rect);
    CGContextSetStrokeColorWithColor(ctf, [UIColor whiteColor].CGColor);
    CGContextStrokePath(ctf);
    UIImage*image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  image;
}


- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

    [_session stopRunning];
    kWeakSelf;
    if ([metadataObjects count] >0){
        dispatch_async(dispatch_get_main_queue(), ^{
            //停止扫描
            [weakself.session stopRunning];
            NSString *stringValue = @"";
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
            stringValue = metadataObject.stringValue;
            if (self.scanSuccessBlock) {
                self.scanSuccessBlock(stringValue);
            }
            [self.navigationController popViewControllerAnimated:YES];
            NSLog(@" 扫描后的url是:%@",stringValue);
            
        });
    }
}

-(BOOL)checkLastAllNum:(NSString *)string{
    NSString *str = [string substringFromIndex:3];
    NSScanner* scan = [NSScanner scannerWithString:str];
    int val;
    return string.length == 7 && [string hasPrefix:@"SYT"] && [scan scanInt:&val] && [scan isAtEnd];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)dealloc{
    NSLog(@"释放二维码%@",NSStringFromClass(self.class));
}

@end
